package com.example.qt.ptplatform.service;

import com.example.qt.ptplatform.entity.Torrent;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.pinecone.clients.Pinecone;
import org.openapitools.db_control.client.model.CreateIndexForModelRequest;
import org.openapitools.db_control.client.model.CreateIndexForModelRequestEmbed;
import org.openapitools.db_control.client.model.DeletionProtection;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.HashMap;

import io.pinecone.clients.Index;
import org.springframework.web.client.RestTemplate;


@Service
public class PineconeService {

    private final Pinecone pinecone;

    @Autowired
    public PineconeService(Pinecone pinecone) {
        this.pinecone = pinecone;
    }



    // 上传到松果向量数据库
    public void upsertTorrentToPinecone(Torrent torrent) {
        try {
            String indexName = "ptplatform-recommendations";
            String namespace = "__default__";

            Index index = pinecone.getIndexConnection(indexName);
            if (index == null) {
                System.out.println("Pinecone 索引连接失败！");
            } else {
                System.out.println("Pinecone 索引连接成功！");
            }

            // 获取向量化后的数据
            String description = torrent.getDescription();
            float[] descriptionVector = vectorizeText(description);  // 调用智谱 AI API 进行向量化

            if (descriptionVector != null) {
                // 将 float[] 向量转换为 List<Float>
                List<Float> vectorList = new ArrayList<>();
                for (float v : descriptionVector) {
                    vectorList.add(v);
                }

                // 构造单条记录的元数据
                Map<String, String> metadata = new HashMap<>();
                metadata.put("description", description);  // 保留原始文本

                // 上传到 Pinecone
                index.upsert("torrent-" + torrent.getTorrentId(), vectorList, namespace);

                System.out.println("已上传向量数据: torrent-" + torrent.getTorrentId());
            } else {
                System.out.println("向量化失败，未上传数据");
            }
        } catch (Exception e) {
            System.out.println("向 Pinecone 上传失败: " + e.getMessage());
        }
    }

    // 调用智谱 API 进行文本向量化
    public float[] vectorizeText(String text) {
        try {
            String apiUrl = "https://open.bigmodel.cn/api/paas/v4/embeddings";  // 智谱 AI 向量化 API URL
            String apiKey = "77f8cb8dd468415d9d21512c3b903e53.7L2VHZWqkNjAiIRK";  // 请替换为你的 API 密钥

            // 设置 HTTP 请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 创建请求体
            String jsonBody = "{\"model\": \"embedding-3\", \"input\": [\"" + text + "\"]}";

            // 创建请求
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

            // 发送 POST 请求并获取响应
            ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class);

            // 解析返回的 JSON 数据
            String responseBody = response.getBody();

            System.out.println("操作的数据是:"+text);

            System.out.println("响应数据: " + responseBody);  // 打印响应内容

            // 使用 Jackson 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonResponse = objectMapper.readTree(responseBody);

            // 提取 embedding 数组
            if (jsonResponse.has("data") && jsonResponse.get("data").isArray()) {
                JsonNode dataNode = jsonResponse.get("data").get(0);  // 假设返回的第一个数据包含向量
                JsonNode embeddingNode = dataNode.get("embedding");

                // 将 embedding 转为 float[] 数组
                float[] vector = new float[embeddingNode.size()];
                for (int i = 0; i < embeddingNode.size(); i++) {
                    vector[i] = (float) embeddingNode.get(i).asDouble();
                }

                return vector;
            } else {
                System.out.println("返回数据不包含嵌入向量");
                return null;
            }
        } catch (Exception e) {
            System.out.println("调用智谱 AI 向量化 API 失败: " + e.getMessage());
            return null;
        }
    }


    public String createIndex() {
        // 创建索引的名称
        String indexName = "ptplatform-recommendations";
        // 指定区域
        String region = "us-east-1";

        // 创建字段映射， "chunk_text" 是文本字段的名字
        HashMap<String, String> fieldMap = new HashMap<>();
        fieldMap.put("text", "chunk_text");

        // 创建嵌入模型配置
        CreateIndexForModelRequestEmbed embed = new CreateIndexForModelRequestEmbed()
                .model("llama-text-embed-v2")  // 使用 Pinecone 提供的模型
                .fieldMap(fieldMap)
                .dimension(2048);  // 这里指定为 2048

        // 使用 Pinecone 客户端创建索引
        try {
            pinecone.createIndexForModel(
                    indexName,
                    CreateIndexForModelRequest.CloudEnum.AWS,
                    region,
                    embed,
                    DeletionProtection.DISABLED,
                    null
            );
            System.out.println("索引创建成功: " + indexName);
            return "索引创建成功";
        } catch (Exception e) {
            System.out.println("索引名字: " + indexName);
            System.out.println("创建索引时出错: " + e.getMessage());
            return "创建索引时出错";
        }
    }
}